package com.chushouya.manager.service.api.impl;


import com.chushouya.manager.dto.admin.login.WebAppLoginUser;
import com.chushouya.manager.dto.admin.login.WebAppUserAuthDTO;
import com.chushouya.manager.service.api.WebAppTokenService;
import com.general.framework.core.constant.Constants;
import com.general.framework.core.enums.ClientTypeEnum;
import com.general.framework.core.exception.CodeEnum;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.IdTakes;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Strings;
import com.general.framework.data.redis.RedisCache;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * app端和web端token验证处理
 * @author leejean team
 */
@Component
@Slf4j
@RefreshScope
public class WebAppTokenServiceImpl implements WebAppTokenService {

    // 令牌秘钥
    @Value("${com.chushouya.manager.login.app.secret}")
    private String secret;

    // 令牌有效期 分钟
    @Value("${com.chushouya.manager.login.app.expireTime}")
    private long expireTime;

    // 单点登录
    @Value("${com.chushouya.manager.login.app.singleSignOn:true}")
    private Boolean singleSignOn;

    private static final long MILLIS_SECOND = 1000;

    private static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_ONE_DAY = MILLIS_MINUTE * 60 * 24;

    @Resource
    private RedisCache redisCache;

    // 移除循环依赖：WebAppTokenServiceImpl 不应该注入自己
    // @Resource
    // private WebAppTokenService webAppTokenService;

    @Override
    public String createToken(WebAppLoginUser loginUser) {
        String userId = String.format("%08d", loginUser.getUserId());
        final String clientType = loginUser.getClientType().toLowerCase();
        String loginUserKey = Strings.format("{}:{}:{}",userId, clientType, IdTakes.takeRandomCode(10));
        final String buildJwtToken = buildJwtToken(loginUserKey);
        loginUser.setLoginUserKey(loginUserKey);
        loginUser.setJwtToken(buildJwtToken);
        if (this.singleSignOn) {
            // 按设备clientType单点登录，异地下线
            Collection<String> keys = redisCache.keys(Constants.APP_LOGIN_TOKEN_KEY.concat(userId).concat(":*"));
            if (Lists.isNotEmpty(keys)) {
                for (String key : keys) {
                    if (!key.startsWith(Constants.APP_LOGIN_TOKEN_KEY + userId + ClientTypeEnum.web.getType())) {
                        // 移动端与web端异地登录不冲突
                        redisCache.deleteObject(key);
                    }
                }
            }
        }
        this.refreshToken(loginUser);
        return buildJwtToken;
    }

    @Override
    public WebAppLoginUser getLoginUser(String jwtToken) {
        // 获取请求携带的令牌
        if (Strings.isNotEmpty(jwtToken)) {
            try {
                String loginUserCacheKey = this.getLoginTokenKey(parseLoginUserKey(jwtToken));
                final WebAppLoginUser webAppLoginUser = redisCache.getCacheObject(loginUserCacheKey);
                if (Objects.nonNull(webAppLoginUser)) {
                    this.verifyToken(webAppLoginUser);
                }
                return webAppLoginUser;
            } catch (Exception e) {
                log.error("获取用户身份信息失败:{}", e.getMessage());
            }
        }
        return null;
    }

    @Override
    public WebAppUserAuthDTO authToken(String token) {
        WebAppLoginUser webAppLoginUser = this.getLoginUser(token);
        if (Objects.isNull(webAppLoginUser)) {
            throw Ex.business(CodeEnum.UNAUTHORIZED);
        }
        WebAppUserAuthDTO appUserAuth = new WebAppUserAuthDTO();
        appUserAuth.setUserId(webAppLoginUser.getUserId());
        appUserAuth.setPhone(webAppLoginUser.getPhone());
        appUserAuth.setUserName(webAppLoginUser.getUserName());
        appUserAuth.setUserType(webAppLoginUser.getUserType());
        appUserAuth.setMerchantId(webAppLoginUser.getMerchantId());
        appUserAuth.setStoreId(webAppLoginUser.getStoreId());
        appUserAuth.setClerkId(webAppLoginUser.getClerkId());
        return appUserAuth;
    }

    @Override
    public void delLoginToken(String jwtToken) {
        if (Strings.isNotEmpty(jwtToken)) {
            String loginUserCacheKey = this.getLoginTokenKey(parseLoginUserKey(jwtToken));
            redisCache.deleteObject(loginUserCacheKey);
        }
    }

    @Override
    public void delLoginToken(Long userId) {
        String userIdStr = String.format("%08d", userId);
        Collection<String> keys = redisCache.keys(Constants.APP_LOGIN_TOKEN_KEY.concat(userIdStr).concat(":*"));
        if (Lists.isNotEmpty(keys)) {
            for (String key : keys) {
                redisCache.deleteObject(key);
            }
        }
    }

    @Async
    @Override
    public void verifyToken(WebAppLoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_ONE_DAY) {
            refreshToken(loginUser);
        }
    }

    @Override
    public void refreshToken(WebAppLoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + (expireTime * MILLIS_MINUTE));
        String loginTokenKey = getLoginTokenKey(loginUser.getLoginUserKey());
        redisCache.setCacheObject(loginTokenKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 从数据声明生成令牌
     * @param loginUserKey 数据声明
     * @return 令牌
     */
    private String buildJwtToken(String loginUserKey) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, loginUserKey);
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 从令牌中获取数据声明
     * @param jwtToken 令牌
     * @return 数据声明
     */
    private String parseLoginUserKey(String jwtToken) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwtToken)
                    .getBody();
            return (String) claims.get(Constants.LOGIN_USER_KEY);
        } catch (Exception e) {
            throw Ex.systemError("parseToken Exception");
        }
    }

    private String getLoginTokenKey(String loginUserKey) {
        return Constants.APP_LOGIN_TOKEN_KEY + loginUserKey;
    }
}
